import { defineStore } from 'pinia'

//类似与localstorage的本地存储
import store from 'store2'

import _ from 'loadsh'



//对象式写法
const useWebsiteStore = defineStore('websiteStore',{
    state() {
        return {
            websites:[]
        }
    },
    actions:{
        add(item) {
            const result = _.find(this.websites,{url:item.url})
            if(result) {
                window.myApi.alert('此网站已经被添加!')
                return
            }
            this.websites.unshift(item)
            store.set('websites',this.websites)
        },
        init() {
            this.websites = store.get('websites') || []
        },
        deleteItem(url) {
            // 找到第一个匹配的元素
            // const result = _.findIndex(this.websites,{url:url})
            
            
            this.websites = this.websites.filter((value) => {
                return value.url !== url
            })
            store.set('websites',this.websites)
        }
    },
    // 这个类似于计算属性
    getters:{
        find() {
            return (keywords) => {
                if(keywords === '') {
                    return this.websites
                }else {
                    // 模糊查询
                    const result = _.filter(this.websites,(item) => {
                        // 定义正则表达式对象, i 表忽略大小写
                        let pattern = new RegExp(keywords,'i')
                        return pattern.test(item.title)
                    })
                    return result
                }
            }
        }
    }
})


export default useWebsiteStore